﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;
using System.Data;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

namespace EWMSWeb.ashx
{
    /// <summary>
    /// HardWare 的摘要说明
    /// </summary>
    public class HardWare : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string result = "";
            try
            {
                if (context.Request["rType"] != null)
                {
                    string rType = context.Request["rType"].Trim();
                    switch (rType)
                    {
                        case "GetEmailList": // 获取可发送邮件的列表
                            result = getToEmailList(int.Parse(context.Request["tab"]));
                            break;
                        case "Hard":
                            HardRecordOper(context);
                            result = "{\"status\":\"OK\"}";
                            break;
                        case "m":
                            result = GetHardModel(int.Parse(context.Request["mid"]),context.Request["other"],context.Request["eType"]).ToString();
                            break;
                        case "goback"://退回上一步
                            CheckBack(int.Parse(context.Request["hardid"]));
                            break;
                        case "upatt":
                            result = UploadFile(context);
                            if (result == "")
                                result = "{\"status\":\"OK\"}";
                            break;
                        case "attlist":
                            string hardid = context.Request["mid"];
                            string CStep = context.Request["CStep"];
                            result = GetAttList(hardid, CStep);
                            break;
                        case "delatt":
                            string attid = context.Request["attid"];
                            result = delAtt(int.Parse(attid));
                            break;
                        case "delemail":

                            break;
                        default:
                            break;

                    }
                }

            }
            catch (Exception ex)
            {
                result = "{\"status\":\"Fail(" + ex.Message + ")\"}";
            }

            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region  硬件表操作
        /// <summary>
        /// 新增送检
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public int HardRecordOper(HttpContext context)
        {
            DataLib.BLL.Hardware bll = new DataLib.BLL.Hardware();
            DataLib.Model.Hardware model = new DataLib.Model.Hardware();
            if (context.Request["hardid"] != null && context.Request["hardid"].Trim() != "" && context.Request["hardid"] != "0")
            {

                model = bll.GetModel(int.Parse(context.Request["hardid"]));
            }
            else
            {
                model.id = 0;
            }
            if (context.Request["txtcjo"] != null && context.Request["txtcjo"].Trim() != "")
            {
                model.cjono = context.Request["txtcjo"];
            }
            if (context.Request["txtload"] != null && context.Request["txtload"].Trim() != "")
            {
                model.loadno = context.Request["txtload"];
            }
            if (context.Request["txtcjoremark"] != null && context.Request["txtcjoremark"].Trim() != "")
            {
                model.cjoremark = context.Request["txtcjoremark"];
            }

            if (context.Request["txtcount"] != null && context.Request["txtcount"].Trim() != "")
            {
                model.boxcount = context.Request["txtcount"];
            }
            if (context.Request["txtcumname"] != null && context.Request["txtcumname"].Trim() != "")
            {
                model.cumname = context.Request["txtcumname"];
            }
            if (context.Request["txtcumcdoe"] != null && context.Request["txtcumcdoe"].Trim() != "")
            {
                model.cumcode = context.Request["txtcumcdoe"];
            }
            if (context.Request["txtman"] != null && context.Request["txtman"].Trim() != "")
            {
                model.saleman = context.Request["txtman"];
            }
            if (context.Request["txtwrldate"] != null && context.Request["txtwrldate"].Trim() != "")
            {
                model.wrldate = context.Request["txtwrldate"];
            }
            if (context.Request["bcity"] != null && context.Request["bcity"].Trim() != "")
            {
                model.bcity = context.Request["bcity"];
            } if (context.Request["gcity"] != null && context.Request["gcity"].Trim() != "")
            {
                model.gcity = context.Request["gcity"];
            }
            if (context.Request["checkdate"] != null && context.Request["checkdate"].Trim() != "")
            {
                model.inspectiondate = context.Request["checkdate"];
            }
            if (context.Request["initremark"] != null && context.Request["initremark"].Trim() != "")
            {
                model.initremark = context.Request["initremark"];
            }
            if (context.Request["initdate"] != null && context.Request["initdate"].Trim() != "")
            {
                model.initcheck = context.Request["initdate"];
            }
            if (context.Request["hardremark"] != null && context.Request["hardremark"].Trim() != "")
            {
                model.hardremark = context.Request["hardremark"];
            }
            if (context.Request["outtime"] != null && context.Request["outtime"].Trim() != "")
            {
                model.outstime = context.Request["outtime"];
            }
            if (context.Request["finshdate"] != null && context.Request["finshdate"].Trim() != "")
            {
                model.hardwarefinish = context.Request["finshdate"];
            }
            if (context.Request["tallyremark"] != null && context.Request["tallyremark"].Trim() != "")
            {
                model.tallyremark = context.Request["tallyremark"];
            }
            if (context.Request["gomemo"] != null && context.Request["gomemo"].Trim() != "")
            {
                model.gocheckremark = context.Request["gomemo"];
            }
            if (model.id != 0)
            {
                if (context.Request["step1"] != null && context.Request["step1"].Trim() != "")
                {
                    string c_old = "";
                    if (model.flag1 == null)
                    {
                        model.flag1 = "";
                    }
                    else
                    {
                        if (model.flag1.Length > 0)
                        {
                            c_old = model.flag1.Substring(model.flag1.Length - 1, 1);
                        }
                    }
                    model.step1 = int.Parse(context.Request["step1"].Trim());
                    //A 初始新增 
                    switch (model.step1)
                    {
                        case 0:
                            if (c_old != "A")
                            {
                                model.flag1 = model.flag1 + "A";    //待送检
                            }
                            break;
                        case 1:
                            if (c_old != "B")
                            {
                                if (model.hardwareno != null && model.hardwareno.Trim() != "")
                                {

                                    if (model.hardno != null && model.hardno.Trim() == model.hardwareno + "01")
                                    {
                                        //已经有硬件测试编号
                                        model.initno = model.hardwareno + "02";
                                    }
                                    else
                                    {
                                        //没有硬件测试编号
                                        model.initno = model.hardwareno + "01";
                                    }
                                }
                                model.flag1 = model.flag1 + "B";    //待初检
                            }
                            break;
                        case 2:
                            if (c_old != "C")
                            {
                                if (model.hardwareno != null && model.hardwareno.Trim() != "")
                                {

                                    if (model.initno != null && model.initno.Trim() == model.hardwareno + "01")
                                    {
                                        //已经有初检编号
                                        model.hardno = model.hardwareno + "02";
                                    }
                                    else
                                    {
                                        //没有初检编号
                                        model.hardno = model.hardwareno + "01";
                                    }
                                }
                                model.flag1 = model.flag1 + "C";    //待硬件
                            }
                            break;
                        case 3:
                            if (c_old != "D")
                            {
                                model.flag1 = model.flag1 + "D";    //待拆解出库
                            }
                            break;
                        case 4:
                            if (c_old != "E")                       //待销售询价
                            {
                                model.flag1 = model.flag1 + "E";
                            }
                            break;
                        case 5:
                            if (c_old != "F")                       //进入查询维护
                            {
                                model.flag1 = model.flag1 + "F";    //进入查询维护
                            }
                            break;
                        default:
                            break;
                    }
                }
                if (bll.Update(model) == true)
                {
                    if (context.Request["emaillist"] != null && context.Request["emaillist"].Length > 10)
                    {
                        string emaillist = context.Request["emaillist"];
                        string cclist = context.Request["cclist"];
                        string content = context.Request["context"];
                        string emailtitle = context.Request["emailtitle"];
                        string uname = context.Request["uname"];
                        if (uname == null)
                        {
                            uname = "admin";
                        }
                        if (context.Request["eType"] != null && context.Request["eType"] == "T")
                        {
                            //理货邮件
                            AddTallyMailList(emaillist,cclist, model.id.ToString(), content, emailtitle, uname);
                        }
                        else
                        { 
                            //询价邮件
                            AddGoCustomerList(emaillist,cclist, model.id.ToString(), content, emailtitle, uname);
                        }
                    }
                    return 0;
                }
                else
                    return -1;
            }
            else
            {
                model.hardwareno =
                model.flag1 = "A";
                if (context.Request["step1"] != null && context.Request["step1"].Trim() != "")
                {
                    model.step1 = int.Parse(context.Request["step1"].Trim());
                }
                return bll.Add(model);
            }

        }


        /// <summary>
        /// 取得对应的硬件送检记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetHardModel(int id, string other,string eType)
        {
            string result = "";
            DataLib.BLL.Hardware bll = new DataLib.BLL.Hardware();
            DataLib.Model.Hardware model = bll.GetModel(id);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            result = serializer.Serialize(model);
            string json = "";
            if(other != null)
            {
                if(other  == "isatt")
                {
                    
                    json = json + ",attlist:" + GetAttList(id.ToString(), "0");
                    
                }
            }
            if (eType != null)
            {
                if (eType == "T")
                {
                    if (json != null && json != "")
                    {
                        json = json + ",emaillist:" + getToEmailList(1);
                    }
                }
                else
                {
                    if (json != null && json != "")
                    {
                        json = json + ",emaillist:" + getToEmailList(2);
                    }
                }
            }

            result = result.Replace("}", json);
            
            result = result + "}";
            return result;
            

        }

        /// <summary>
        /// 统一退回上一步  FLAG1 代表历史步骤  A(新增）B（送检）C（初检）D(硬件测试）E（出库)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string CheckBack(int id)
        {
            DataLib.BLL.Hardware bll = new DataLib.BLL.Hardware();
            DataLib.Model.Hardware model = bll.GetModel(id);

            if (model != null)
            {

                if (model.flag1.Length > 1)
                {
                    model.flag1 = model.flag1.Substring(0, model.flag1.Length - 1);
                }
                string step = model.flag1.Substring(model.flag1.Length - 1, 1);
                switch (step)
                {
                    case "A":
                        model.step1 = 0;    //待送检
                        break;
                    case "B":
                        model.step1 = 1;    //待初检
                        break;
                    case "C":
                        model.step1 = 2;    //待硬件测试
                        break;
                    case "D":
                        model.step1 = 3;    //待出库理货
                        break;
                    case "E":
                        model.step1 = 4;    //已经完成
                        break;
                    default:
                        break;
                }

            }

            return bll.Update(model).ToString();

        }
        #endregion

        #region  邮件相关


        #region 询价邮件

        public string AddGoCustomerList(string iemaillist,string cemaillist, string hardid, string emalcontext, string title, string uname)
        {
            DataLib.Accounts.Bus.User u = new DataLib.Accounts.Bus.User(uname);
            
            string result = "{\"status\":\"ok\"}";

            DataLib.Model.DoCustomerList m = new DataLib.Model.DoCustomerList();
            DataLib.BLL.DoCustomerList bll = new DataLib.BLL.DoCustomerList();
            DataLib.BLL.CCEmailList cbll = new DataLib.BLL.CCEmailList();
            DataLib.BLL.AttachHard abll = new DataLib.BLL.AttachHard();
            DataLib.BLL.PEmail p = new DataLib.BLL.PEmail();
            DataLib.Model.CCEmailList cm = new DataLib.Model.CCEmailList();
            if (hardid != null && hardid != "0" && u != null)
            {
                DataLib.Model.Hardware hm = new DataLib.BLL.Hardware().GetModel(int.Parse(hardid));
                if (hm != null)
                {
                    List<DataLib.Model.PEmail> ilist = new List<DataLib.Model.PEmail>();
                    List<DataLib.Model.PEmail> clist = new List<DataLib.Model.PEmail>();
                    List<DataLib.Model.AttachHard> alist = new List<DataLib.Model.AttachHard>();
                    ilist = p.GetEList(iemaillist,"I");
                    clist = p.GetEList(cemaillist,"CC");
                    alist = abll.GetModelList("Hardid=" + hardid);
                    string  eno = bll.GetMaxNoByHardid(hardid);
                    if (eno != null && eno != "0")
                    {
                        //DataLib.Model.DoCustomer dm = new DataLib.Model.DoCustomer();
                        //dm.companyname
                        int no = int.Parse(eno.Substring(eno.Length - 1, 1)) + 1;
                        eno = hm.hardwareno + "eMail" + no.ToString().PadLeft(2, '0');
                    }
                    else
                    {
                        eno = hm.hardwareno + "eMail" + "01";
                    }
                    
                    m.hardid = int.Parse(hardid);
                    m.hardno = hm.hardwareno;
                    m.emailadd = iemaillist;
                    m.truename = p.GetStrEList(iemaillist, "I");
                    m.flag2 = eno;//邮件编号
                    m.emailcontent = emalcontext;
                    m.createtime = DateTime.Now;
                    m.flag1 = title;

                    cm.hardid = m.hardid;
                    cm.hardno = m.hardno;
                    cm.emailadd = emalcontext;
                    cm.CCType = 0;
                    cm.emailcontent = emalcontext;
                    cm.ccusers = p.GetStrEList(cemaillist,"CC");
                    cm.createtime = DateTime.Now;
                    cm.flag2 = "CC" + eno;
                    try
                    {
                        cbll.Add(cm);
                        bll.Add(m);
                        SendsEmail(u,alist,ilist, clist, title, emalcontext, m.truename, "SMTP.tes-amm.cn", "a1b2c3d");
                    }
                    catch (Exception ex)
                    {
                        //ex.Message;
                    }
                    //foreach (Email l in ilist)
                    //{
                       
                    //   // m.emailid = l.id;
                    //    //m.emailcontent = emalcontext;
                    //    //m.emailadd = l.email;
                    //    //m.truename = l.tname; //l.companyname;
                    //    m.flag1 = title;    //邮件标题
                    //    m.createtime = DateTime.Now;
                    //    //
                    //    SendEmail(u, m.emailadd, title, m.truename, emalcontext, "", "SMTP.tes-amm.cn", "a1b2c3d");
                    //    bll.Add(m);
                    //}
                }
            }
            return result;
        }
        #endregion

        #region 理货邮件

        /// <summary>
        /// 增加记录
        /// </summary>
        /// <param name="json"></param>
        /// <param name="hardid"></param>
        /// <param name="emalcontext"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public string AddTallyMailList(string iemaillist, string cemaillist, string hardid, string emalcontext, string title, string uname)
        {

            DataLib.Accounts.Bus.User u = new DataLib.Accounts.Bus.User(uname);

            string result = "{\"status\":\"ok\"}";

            DataLib.Model.TallyEmailList m = new DataLib.Model.TallyEmailList();
            DataLib.BLL.TallyEmailList bll = new DataLib.BLL.TallyEmailList();
            DataLib.BLL.CCEmailList cbll = new DataLib.BLL.CCEmailList();
            DataLib.BLL.AttachHard abll = new DataLib.BLL.AttachHard();
            DataLib.BLL.PEmail p = new DataLib.BLL.PEmail();
            DataLib.Model.CCEmailList cm = new DataLib.Model.CCEmailList();
            if (hardid != null && hardid != "0" && u != null)
            {
                DataLib.Model.Hardware hm = new DataLib.BLL.Hardware().GetModel(int.Parse(hardid));
                if (hm != null)
                {
                    List<DataLib.Model.PEmail> ilist = new List<DataLib.Model.PEmail>();
                    List<DataLib.Model.PEmail> clist = new List<DataLib.Model.PEmail>();
                    List<DataLib.Model.AttachHard> alist = new List<DataLib.Model.AttachHard>();
                    ilist = p.GetEList(iemaillist, "I");
                    clist = p.GetEList(cemaillist, "CC");
                    alist = abll.GetModelList("Hardid=" + hardid);
                    string eno = bll.GetMaxNoByHardid(hardid);
                    if (eno != null && eno != "0")
                    {
                        //DataLib.Model.DoCustomer dm = new DataLib.Model.DoCustomer();
                        //dm.companyname
                        int no = int.Parse(eno.Substring(eno.Length - 1, 1)) + 1;
                        eno = hm.hardwareno + "eMail" + no.ToString().PadLeft(2, '0');
                    }
                    else
                    {
                        eno = hm.hardwareno + "eMail" + "01";
                    }

                    m.hardid = int.Parse(hardid);
                    m.hardno = hm.hardwareno;
                    m.emailadd = iemaillist;
                    m.truename = p.GetStrEList(iemaillist, "I");
                    m.flag2 = eno;//邮件编号
                    m.emailcontent = emalcontext;
                    m.createtime = DateTime.Now;
                    m.flag1 = title;

                    cm.hardid = m.hardid;
                    cm.hardno = m.hardno;
                    cm.emailadd = emalcontext;
                    cm.CCType = 0;
                    cm.emailcontent = emalcontext;
                    cm.ccusers = p.GetStrEList(cemaillist, "CC");
                    cm.createtime = DateTime.Now;
                    cm.flag2 = "CC" + eno;
                    try
                    {
                        cbll.Add(cm);
                        bll.Add(m);
                        SendsEmail(u, alist, ilist, clist, title, emalcontext, m.truename, "SMTP.tes-amm.cn", "a1b2c3d");
                    }
                    catch (Exception ex)
                    {
                        //ex.Message;
                    }
                }
            }
            return result;

        }
        #endregion


        #region 公用
        /// <summary>
        /// 删除邮件联系人
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tab">1是理货邮件 2是下家</param>
        protected string del(int id, int tab)
        {
            string result = "";
            if (tab == 1)
            {
                DataLib.BLL.TallyEmail tb = new DataLib.BLL.TallyEmail();
                tb.Delete(id);
            }
            else if (tab == 2)
            {
                DataLib.BLL.DoCustomer cb = new DataLib.BLL.DoCustomer();
                cb.Delete(id);
            }
            return result;
        }

        /// <summary>
        /// 取得邮件联系人的全体列表
        /// </summary>
        /// <param name="tab">1为理货,2为询价邮件</param>
        /// <returns></returns>
        protected string getToEmailList(int tab)
        {
            DataTable dt = new DataTable();
            if (tab == 1)
            {
                //理货
                dt = new DataLib.BLL.TallyEmail().GetAllList().Tables[0];
                
            }
            else if (tab == 2)
            {
                dt = new DataLib.BLL.DoCustomer().GetAllList().Tables[0];
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                return DataTableToJsonWithJavaScriptSerializer(dt);
            }
            else
            {
                return "{\"status\":\"OK\"}";
            }
        }

      /// <summary>
      /// 发送邮件
      /// </summary>
      /// <param name="u">发送邮件的用户</param>
      /// <param name="toemail">接收邮件的Email地址</param>
      /// <param name="title">邮件标题</param>
      /// <param name="linkman">接收人昵称</param>
      /// <param name="content">邮件主体内容</param>
      /// <param name="tempno">邮件模板</param>
      /// <param name="ServiceName">发送邮件的服务器名称</param>
      /// <param name="eailpwd">邮箱密码</param>
        public string SendEmail(DataLib.Accounts.Bus.User u, string toemail, string title, string linkman, string content, string tempno, string ServiceName, string eailpwd)
        {
            string result = "";
            #region//设置邮件信息
            MailMessage message = new MailMessage();//实例化邮件主体
            message.From = new MailAddress(u.Email, u.TrueName);//发信人地址
            message.To.Add(new MailAddress(toemail, linkman));//收信人地址
            message.Subject = title;//邮件主题
            message.Body = content;//邮件主体：正文
            message.IsBodyHtml = true;//主体是否是html格式
            MailAddress m = new MailAddress("","");
            message.CC.Add(m);
            #endregion
            //#region//获取所有邮件附件
            //char[] cr = { ';' };
            //string[] file = m_file.Split(cr);
            //for (int n = 0; n < file.Length; n++)
            //{
            //    if (file[n] != "")
            //    {
            //        //附件对象
            //        Attachment data = new Attachment(file[n], MediaTypeNames.Application.Octet);
            //        //附件资料
            //        ContentDisposition disposition = data.ContentDisposition;
            //        disposition.CreationDate = System.IO.File.GetCreationTime(file[n]);
            //        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file[n]);
            //        disposition.ReadDate = System.IO.File.GetLastAccessTime(file[n]);
            //        //加入邮件附件
            //        message.Attachments.Add(data);
            //    }
            //}
            //#endregion
            #region//设置发送邮件的smtp服务器信息
            try
            {
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();//实例化发送邮件的smtp服务器
                smtpClient.Host = ServiceName;//服务器的名称
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定处理邮件的方式，此处为通过网络发送到smtp服务器
                smtpClient.Credentials = new System.Net.NetworkCredential(u.Email, eailpwd);//验证发件人身份，用户名kaixiyeetop，密码******
                
                smtpClient.Send(message);//发送邮件
                result = "{\"status\":\"OK\"}";
            }
            catch (Exception ex)
            {
                result = "{\"status\":\"失败：" + ex.Message + "\"}";
            }
            return result;
            #endregion
        }


        /// <summary>
        /// 发送邮件有抄送人
        /// </summary>
        /// <param name="u">发送邮件的用户</param>
        /// <param name="toemail">接收邮件的Email地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="linkman">接收人昵称</param>
        /// <param name="content">邮件主体内容</param>
        /// <param name="tempno">邮件模板</param>
        /// <param name="ServiceName">发送邮件的服务器名称</param>
        /// <param name="eailpwd">邮箱密码</param>
        public string SendsEmail(DataLib.Accounts.Bus.User u,List<DataLib.Model.AttachHard> alist, List<DataLib.Model.PEmail> tolist,List<DataLib.Model.PEmail> cclist, string title, string content, string tempno, string ServiceName, string eailpwd)
        {
            string result = "";
            #region//设置邮件信息
            MailMessage message = new MailMessage();//实例化邮件主体
            message.From = new MailAddress(u.Email, u.TrueName);//发信人地址
           
            message.Subject = title;//邮件主题
            message.Body = content;//邮件主体：正文
            message.IsBodyHtml = true;//主体是否是html格式

            string fa = "";
            try
            {
                foreach (DataLib.Model.AttachHard a in alist)
                {


                    //string a1 = dsd.Query.ToString();
                    //fa = Server.MapPath("~/") + a.AttacheName;
                    message.Attachments.Add(new Attachment(a.flag1));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            foreach (DataLib.Model.PEmail m in cclist)
            {
                message.CC.Add(new MailAddress(m.value, m.lable));//收信人地址
            }
         
            #endregion
            //#region//获取所有邮件附件
            //char[] cr = { ';' };
            //string[] file = m_file.Split(cr);
            //for (int n = 0; n < file.Length; n++)
            //{
            //    if (file[n] != "")
            //    {
            //        //附件对象
            //        Attachment data = new Attachment(file[n], MediaTypeNames.Application.Octet);
            //        //附件资料
            //        ContentDisposition disposition = data.ContentDisposition;
            //        disposition.CreationDate = System.IO.File.GetCreationTime(file[n]);
            //        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file[n]);
            //        disposition.ReadDate = System.IO.File.GetLastAccessTime(file[n]);
            //        //加入邮件附件
            //        message.Attachments.Add(data);
            //    }
            //}
            //#endregion
            #region//设置发送邮件的smtp服务器信息
            try
            {
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();//实例化发送邮件的smtp服务器
                smtpClient.Host = ServiceName;//服务器的名称
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定处理邮件的方式，此处为通过网络发送到smtp服务器
                smtpClient.Credentials = new System.Net.NetworkCredential(u.Email, eailpwd);//验证发件人身份，用户名kaixiyeetop，密码******
                foreach (DataLib.Model.PEmail e in tolist)
                {
                    message.To.Add(new MailAddress(e.value, e.lable));//收信人地址
                    smtpClient.Send(message);//发送邮件
                    message.To.Clear();
                }
               
                result = "{\"status\":\"OK\"}";
            }
            catch (Exception ex)
            {
                result = "{\"status\":\"失败：" + ex.Message + "\"}";
            }
            return result;
            #endregion
        }
        #endregion
        #endregion

        #region 附件相关
        public string UploadFile(HttpContext con)
        {
            string result = "";
            DataLib.Model.AttachHard model = new DataLib.Model.AttachHard();
            DataLib.DAL.AttachHard dal = new DataLib.DAL.AttachHard();


            if (con.Request.Files.Count > 0)
            {
                if (con.Request["hardid"] != null)
                {
                    int hardid = int.Parse(con.Request["hardid"].ToString());
                    DataLib.Model.Hardware hard = new DataLib.DAL.Hardware().GetModel(hardid);
                    HttpPostedFile file = con.Request.Files[0];

                    model.HardNo = hard.hardwareno;

                    if (con.Request["CStep"] != null)
                    {
                        int CStep = int.Parse(con.Request["CStep"].Trim());
                        switch (CStep)
                        {
                            case 1:
                                model.CreateStep = "初检";
                                model.BillNo = hard.initno;
                                break;
                            case 2:
                                model.CreateStep = "硬件";
                                model.HardNo = hard.hardno;
                                break;
                            default:
                                break;

                        }

                    }
                    String fileName = System.IO.Path.GetFileName(file.FileName);
                    model.AttacheName = fileName;

                    string TimePath = con.Server.MapPath("~/Upload/Hard/" + model.BillNo) + "\\";//获取上传路径的物理地址 
                    if (!Directory.Exists(TimePath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(TimePath);//不存在则创建文件夹 
                    }
                    fileName = con.Server.MapPath("~/Upload/Hard/" + model.BillNo + "/") + fileName;
                    file.SaveAs(fileName);

                    model.CreateMan = "admin";
                    model.flag1 = fileName;

                    model.hardid = hardid;
                    model.Createtime = DateTime.Now;
                    model.id = dal.Add(model);
                    result = new JavaScriptSerializer().Serialize(model);
                }
            }
            return result;

        }

        /// <summary>
        /// 获取附件列表的JSON格式
        /// </summary>
        /// <param name="hardid"></param>
        /// <param name="CStep"></param>
        /// <returns></returns>
        public string GetAttList(string hardid, string CStep)
        {
            string result = "";
            DataTable dt = new DataTable();
            DataLib.BLL.AttachHard bll = new DataLib.BLL.AttachHard();
            string where = "";
            switch (CStep)
            {
                case "1":
                    where = " and CreateStep='初检'";
                    break;
                case "2":
                    where = " and CreateStep='硬件'";
                    break;
                case "0":
                    where = "";
                    break;
                default:
                    where = CStep;
                    break;
            }
            dt = bll.GetList("hardid=" + hardid + where).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                result = DataTableToJsonWithJavaScriptSerializer(dt);
            }
            else
            {
                result = "[{\"AttacheName\":\"无附件\",\"id\":0}]";
            }
            return result;

        }

        /// <summary>
        /// 删除附件记录及文件
        /// </summary>
        /// <param name="attid"></param>
        /// <returns></returns>
        public string delAtt(int attid)
        {
            string result = "";
            DataLib.BLL.AttachHard bll = new DataLib.BLL.AttachHard();
            DataLib.Model.AttachHard m = bll.GetModel(attid);
            if (m != null)
            {
                if (bll.DelFile(attid))
                {
                    result = GetAttList(m.hardid.ToString(), m.CreateStep);
                }
            }
            return result;
        }
        #endregion


        /// <summary>
        /// datatable 转JSON
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public string DataTableToJsonWithJavaScriptSerializer(DataTable table)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            Dictionary<string, object> childRow;
            foreach (DataRow row in table.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    childRow.Add(col.ColumnName, row[col]);
                }
                parentRow.Add(childRow);
            }
            return jsSerializer.Serialize(parentRow);
        }


        /// <summary>
        /// 将json数据转换成邮件列表 
        /// </summary>
        /// <returns></returns>
        private static List<Email> GetEmailList(string jsonString)
        {
            // 实例化DataContractJsonSerializer对象，需要待序列化的对象类型
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Email>));
            List<Email> ls = null;
            //把Json传入内存流中保存
            if(jsonString.IndexOf("]")<0)
                jsonString = "[" + jsonString + "]";
            try
            {
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                // 使用ReadObject方法反序列化成对象
                object ob = serializer.ReadObject(stream);
                 ls = (List<Email>)ob;
            }
            catch (Exception ex)
            {
                jsonString = ex.Message;
            }
            return ls;
        }

        /// <summary>
        /// 将json数据转换成邮件列表 
        /// </summary>
        /// <returns></returns>
        private static List<Email> GetString(string jsonString,int T)
        {
            // 实例化DataContractJsonSerializer对象，需要待序列化的对象类型
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Email>));
            List<Email> ls = null;
            //把Json传入内存流中保存
            if (jsonString.IndexOf("]") < 0)
                jsonString = "[" + jsonString + "]";
            try
            {
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                // 使用ReadObject方法反序列化成对象
                object ob = serializer.ReadObject(stream);
                ls = (List<Email>)ob;
            }
            catch (Exception ex)
            {
                jsonString = ex.Message;
            }
            return ls;
        }





    }

    [Serializable]
    public class Email
    {
        public int id;
        public string tname;
        public string email;
        public string flag1;
    }




}